import { HttpMethod, JavaNetParams, PhpNetModel } from "./NetParams.ts";
import { getNetDefense } from "../../Native/Module/Crypto.ts";

const BASE_URL = "https://yupao-test.yupaowang.com/";

function genHeader(headers: {} | undefined): {} {
  const version = "6.0.1";
  const token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE3MDU3MTY3MjMsImV4cCI6MTcxNjA4NDcyMywiZGF0YSI6eyJzaW5nbGUiOiJXSk0zMkg1U0dQSFA0TURBIiwidWlkIjoyMDA1NzE0MiwiYnVzaW5lc3MiOiIxIiwic3lzdGVtX3R5cGUiOiJhbmRyb2lkIiwibWluaV90b2tlbiI6IldKTTMySDVTR1BIUDRNREEiLCJpZCI6MjAwNTcxNDIsInV1aWQiOjIwMDU3MTQyfSwidG9rZW4iOnsicmVnUnQiOiJhbmRyb2lkIiwidGVuYW50S2V5IjoiWVBaUCIsInRlbmFudElkIjoyMDA1NzE0MiwicGFja2FnZU5hbWUiOiJpby5kY2xvdWQuSDU3NkU2Q0M3IiwidXNlcklkIjoyMDA1NzE0MiwidG9rZW4iOiJXSk0zMkg1U0dQSFA0TURBIn19.6hwDZq0zumVbOFsiwf3-uaNwgArLV9I6Vq8D--sFpzU";
  const netDefense = getNetDefense(token, version);
  return {
    versioncode: "300601161",
    systemversion: "13",
    version: version,
    version_code: "300601161",
    channel: "dev",
    device: "vivo,V2219A",
    system: "android",
    system_type: "android",
    package_name: "H576E6CC7",
    packageName: "io.dcloud.H576E6CC7",
    business: "1",
    reqsource: "YPZP",
    deviceuuid: "android",
    uid: "20057142",
    uuid: "1636444426623914",
    singletoken: token,
    token: token,
    userrole: "2",
    "x-yp-nonce": netDefense["x-yp-nonce"],
    "x-yp-sign": netDefense["x-yp-nonce"],
    imei: "",
    oaid: "5519b691e4d153f33f7f4af2d9ab4e449137af58386e93550ba8709002c4936e",
    meid: "",
    track_seed: "",
    "user-agent": "YP YPZP vivo V2219A 13 6.0.1 36d924c55567b9dd 1705630886606",
    occversion: "2",
    ...headers
  };
}


async function phpFetch<T>(params: JavaNetParams) {
  const url = `${BASE_URL}${params.url}`;
  const method = (params.method || HttpMethod.POST).valueOf();
  return fetch(url, {
    body: JSON.stringify(params.params),
    method: method,
    headers: genHeader(params.headers)
  }).then(async response => {
    let json = await response.json();
    console.log(`php url=${url} result=${JSON.stringify(json)}`);
    return json as PhpNetModel<T>;
  });
}

export default phpFetch;
